from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
# Create your views here.
from apps import models
def check_login(func):
    def warpper(request,*args,**kwargs):
        is_login=request.session.get('IS_LOGIN',False)
        if is_login:
            return func(request,*args,**kwargs)
        else:
            return HttpResponseRedirect("/login")
        return warpper
def login_view(request):
    if request.method=="POST":
        user_name=request.POST.get('user_name','')
        pass_word=request.POST.get('pwd','')
        user=models.User.objects.get(user_name=user_name,pwd=pass_word)
        if user:
            if pass_word==user.pwd:
                request.session['IS_LOGIN']=True
                request.session['user_name']=user_name
                request.session['user_id']=user.id
                return render(request,'index.html',{'user_name':user_name})
            else:
                return render(request,'login.html',{'error':'用户名或密码错误'})
        else:
            return render(request,'login.html',{'error':'用户名不存在'})
    elif request.method=="GET":
        return  render(request,'login.html')
    else:
        return render(request,'login.html')
def login_out(request):
    request.session.flush()
    return render(request,'login.html')
def register_viem(request):
    if request.method=="GET":
        return render(request,'register.html')
    if request.method == "POST":
        user_name = request.POST.get('user_name', '')
        pass_word_1= request.POST.get('pwd', '')
        pass_word_2= request.POST.get('cpwd', '')
        phone=request.POST.get('phone','')
        if models.User.objects.get(user_name=user_name):
            return render(request,'register.html',{'error':'用户也存在'})
        if pass_word_1 !=pass_word_2:
            return render(request, 'register.html', {'error': '两次输入密码请输入一致'})
        user=models.User()
        user.user_name=user_name
        user.user.pwd=pass_word_1
        user.phone=phone
        user.save()
        return render(request,'login.html')
    else:
        return render(request,'register.html')
def index_viem(request):
   # goods_list=models.Goods.objects.all()
   types=models.Type.objects.all()
   dic={}
   for type in types:
       list=models.Goods.objects.filter(type__id=type.id)
       dic[type.type_name]=list
   # return render(request,'index.html',{"goods_list":goods_list,"user_name":request.session.get('user_name',None)})
   return render(request, 'index.html', {"goods_type":types," goods_list":dic, "user_name": request.session.get('user_name', None)})
def goodDetail(request,id):
    good_detail=models.Goods.objects.all(id+id)
    return render(request,'detail.html',{"goods_list":good_detail,"user_name":request.session.get('user_name',None)})